<!-- 单位编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="800"
    :model-value="modelValue"
    title="商品移库"
    @update:model-value="updateModelValue"
  >
    <template #header>
      <div class="flex-a">
        <div class="flex-shrink-0">商品移库</div>
        <div class="flex-a ml-30px">
          <div>新库位：</div>
          <el-cascader
            v-model="locationId"
            :options="locationTree"
            filterable
            clearable
            placeholder="请选择库位"
            :show-all-levels="false"
            placement="left"
            :props="{ value: 'id', label: 'name', expandTrigger: 'hover', emitPath: false }"
          />
          <el-button type="primary" :disabled="!locationId" plain class="ml-10px" @click="batchLocation">批量设置</el-button>
          <el-divider class="mx-20px" direction="vertical" />
          <el-button type="" @click="showProduct = true">添加商品</el-button>
        </div>
      </div>
    </template>
    <el-form ref="formRef" :model="form" :rules="{}" label-width="auto">
      <el-table ref="tableRef" height="55vh" :data="form.product" size="small">
        <el-table-column type="index" label="序" width="40" align="left" />
        <el-table-column prop="product_name" label="商品名称" width="" />
        <el-table-column prop="product_code" label="商品编码" align="center" width="120" />
        <el-table-column prop="location_name" label="原库位" align="center" width="160" />
        <el-table-column prop="new_location_id" label="新库位" align="center">
          <template #default="{ $index }">
            <div class="flex-c">
              <el-form-item
                :label-width="0"
                :prop="`product[${$index}].new_location_id`"
                required
                :rules="ruleLoc"
                class="mb-0!"
              >
                <el-cascader
                  v-model="form.product[$index].new_location_id"
                  :options="locationTree"
                  size="small"
                  filterable
                  clearable
                  placeholder="请选择库位"
                  :show-all-levels="false"
                  placement="left"
                  :props="{ value: 'id', label: 'name', expandTrigger: 'hover', emitPath: false }"
                />
              </el-form-item>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <template #footer>
      <el-button @click="updateModelValue(false)">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
    <SelectProduct
      v-model="showProduct"
      :selecteds="form.product"
      :where="{ warehouse_id: props.warehouseId, is_location: 1 }"
      :showPirce="false"
      :editNum="false"
      @done="selectProduct"
    />
  </ele-modal>
</template>

<script setup>
import { listWlList } from '@/api/common'
import SelectProduct from '@/components/Common/SelectProduct/index.vue'

import { toTree } from 'ele-admin-plus/es'

const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  /** 修改回显的数据 */
  data: Object,
  warehouseId: Number,
})

const emit = defineEmits(['done', 'update:modelValue'])

const locationId = ref()

const showProduct = ref(false)

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)
const tableRef = ref(null)

const ruleLoc = [{ required: true, trigger: ['change', 'blur'] }]

/** 表单数据 */
const [form, resetFields] = utils.useFormData({
  product: [],
})

const locationTree = ref([])

function getLocationTree() {
  listWlList(props.warehouseId).then((res) => {
    locationTree.value = toTree({
      data: res.data,
      idField: 'id',
      parentIdField: 'pid',
    })
  })
}

function selectProduct(data) {
  data.forEach((v) => {
    const loac = v.location?.[0] ?? {}
    v.location_id = loac.id
    v.location_name = loac.name
  })
  form.product.push(...data)

  // setTimeout(() => {
  //   tableRef.value.doLayout()
  // }, 200)
}

function batchLocation() {
  form.product.forEach((v) => {
    v.new_location_id = locationId.value
  })
  formRef.value?.clearValidate?.()
}

/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    utils.post('/stockMove/edit', {
      warehouse_id: props.warehouseId,
      product: form.product.map(v => ({
        product_id: v.product_id,
        old_location_id: v.location_id,
        new_location_id: v.new_location_id,
      })),
    })
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          updateModelValue(false)
          emit('done')
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (modelValue) {
      if (props.data) {
        form.product = [...props.data]
        getLocationTree()
      }
    }
    else {
      resetFields()
      formRef.value?.clearValidate?.()
      locationId.value = 0
    }
  },
)
</script>
